# Replication package for 
# "The Economic Leverage of International Organizations in Interstate Disputes"
# Johannes Karreth
# June 30, 2017
# jkarreth@ursinus.edu

# This file: 50_hligo_geo.R
# Purpose: Show temporal patterns of state memberships in IGOs with high leverage

rm(list = ls())

# setwd("...")

library("rio")
library("reshape2")
library("dplyr")
library("ggplot2")
library("ggrepel")

# Source in functions
source("Functions/theme_jk.R")

igo_num <- import("igo_overlap_num.csv")
igo_names <- import("Sources/IGO_names_v2.3.csv")
igo_lev3_count_use <- igo_names[igo_names$ionum %in% igo_num$igo_lev3_count_use, ]$IONAME

hligos <- igo_num[is.na(igo_num$igo_lev3_count_use) == FALSE, 1]

members <- import("Sources/IGO_stateunit_v2.3.csv")
hligo_members <- members[ , names(members) %in% igo_lev3_count_use]
hligo_idvars <- members[, c("ccode", "country", "year")]
hligo_members <- cbind(hligo_idvars, hligo_members)

head(hligo_members)

hligo_years <- melt(hligo_members, id.vars = c("ccode", "country", "year"))
hligo_years$member <- ifelse(hligo_years$value == 1, 1, 0)
hligo_years$value <- NULL

hligo_count <- summarize(group_by(hligo_years, variable, year),
                         members = sum(member))

hligo_count <- hligo_count[hligo_count$year > 1945 & hligo_count$year <= 2000, ]

p <- ggplot(data = hligo_count[hligo_count$members > 0, ], aes(x = year, y = members, group = variable, color = variable)) + 
      geom_line() + 
      geom_text_repel(
        data = subset(hligo_count, year == max(year)),
        aes(label = variable),
        # size = 6,
        # nudge_x = 45,
        segment.color = NA
        ) + theme_jk() + 
      theme(legend.position = "none")